package com.example.administrator.lrucachedemo

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.util.Log
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL

class BitmapThread(private val bitmapUrl: String,
                   private val imageDownLoader: ImageDownLoader,
                   private val handler: Handler) : Thread() {
    override fun run() {
        Log.i(TAG, "run:" + Thread.currentThread().name)
        var bitmap: Bitmap? = null
        var connection: HttpURLConnection? = null
        var inputStram: InputStream? = null
        try {
            val url=URL(bitmapUrl)
            connection= url.openConnection() as HttpURLConnection?
            connection?.connectTimeout=5000
            connection?.requestMethod="GET"
            if(connection?.responseCode==HttpURLConnection.HTTP_OK){
                inputStram=connection.inputStream
                bitmap=BitmapFactory.decodeStream(inputStram)
            }
            if(bitmap!=null){
                imageDownLoader.addBitmapToMemory(bitmapUrl,bitmap)
            }
            handler.obtainMessage(110,bitmap).sendToTarget()
        }catch (e:Exception){
            e.printStackTrace()
        }finally {
            connection?.disconnect()
            inputStram?.close()
        }

    }

    companion object {
        private val TAG = "BitmapThread子线程下载"
    }
}